package com.hbgc.config;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@ComponentScan("com.hbgc")
@MapperScan("com.hbgc.mapper")
public class AppConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setUsername("eshop");
        basicDataSource.setPassword("123456");
        basicDataSource.setUrl("jdbc:mysql://wdjm.cloud:3306/eshop?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false");
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        factoryBean.setDataSource(basicDataSource);

        //别名设置
        factoryBean.setTypeAliasesPackage("com.hbgc.entity");


        //配置映射文件xml
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/*.xml");
        factoryBean.setMapperLocations(resources);

        //设置settings
        Configuration configuration = new Configuration();
        configuration.setLogImpl(Log4jImpl.class);          //设置日志使用log4j
        configuration.setMapUnderscoreToCamelCase(true);    //开启驼峰命名
        factoryBean.setConfiguration(configuration);

        return factoryBean.getObject();
    }
}
